package org.dev.vlp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.dev.vlp.entity.Tag;
import org.dev.vlp.exception.ApiException;
import org.dev.vlp.service.TagService;
import org.dev.vlp.mapper.TagMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
* @author 86184
* @description 针对表【vlp_tag】的数据库操作Service实现
* @createDate 2023-01-08 18:46:59
*/
@Service
public class TagServiceImpl extends ServiceImpl<TagMapper, Tag>
    implements TagService{

    @Autowired
    private TagMapper tagMapper;

    @Override
    public List<Tag> getBelowTags(int tagId,int userId) {
        return tagMapper.getTags(tagId,userId);
    }

    @Override
    public void createTag(Tag tag, int userId) {
        tag.setCreatorId(userId);
        int insert = tagMapper.insert(tag);
        if(insert<=0){
            throw new ApiException("创建失败");
        }
    }

    @Override
    public void modifyTag(Tag tag, int userId) {
//        System.out.println(tag);
        if(tag==null||tag.getCreatorId()!=userId){
            throw new ApiException("无权限修改");
        }
        if(tagMapper.updateById(tag)<=0){
            throw new ApiException("修改失败");
        }
    }

    @Override
    public void deleteTag(List<Integer> tagIds,int userId) {
        HashSet<Integer> integers = new HashSet<>();
        QueryWrapper<Tag> tagQueryWrapper = new QueryWrapper<>();
        tagQueryWrapper.in("tag_id",tagIds);
        List<Tag> tags = tagMapper.selectList(tagQueryWrapper);
        for(Tag tag:tags){
            Integer tagId = tag.getTagId();
            Integer creatorId = tag.getCreatorId();
            // 二级或一级判断是否为创建用户
            if(creatorId==userId){
                integers.add(tagId);
                if(tag.getParentId()==0){
                    List<Integer> childTagId = tagMapper.getChildTagId(tagId);
                    integers.addAll(childTagId);
                }
            }
        }
        if (CollectionUtils.isEmpty(integers)){
            throw new ApiException("没有你创建的标签需要删除");
        }

        UpdateWrapper<Tag> tagUpdateWrapper = new UpdateWrapper<>();
        tagUpdateWrapper.set("is_deleted",1).in("tag_id",integers);
        if(tagMapper.update(null,tagUpdateWrapper)<=0){
            throw new ApiException("删除失败");
        }
    }
}




